package ee.subjects.backend.model.dao.postgresqlimplementation;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.log4j.Logger;

import ee.subjects.backend.database.ConnectionManager;
import ee.subjects.backend.model.dao.Subject_type_DAO;
import ee.subjects.backend.model.data.Subject_type;

public class Subject_type_DAOPostgresImpl implements Subject_type_DAO
{
	Logger logger = Logger.getLogger(Subject_type_DAOPostgresImpl.class);
	Connection dbConnection;
	String sql;
	PreparedStatement preparedStatement;
	Statement statement;
	ResultSet resultSet;
	
	public Subject_type_DAOPostgresImpl(Connection dbConnection) 
	{
		this.dbConnection = dbConnection;
	}
	
	
	@Override
	public Subject_type findSubject_typeById(int subject_typeId) 
	{
		Subject_type subject_typeRetrieved = null;
		resultSet = null;
		sql = "SELECT * FROM subject_type WHERE subject_type = ?";
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(
						sql,
						ResultSet.TYPE_SCROLL_INSENSITIVE,
						ResultSet.CONCUR_READ_ONLY
					);
			//filling the placeholders 
			preparedStatement.setInt(1, subject_typeId);
			resultSet = preparedStatement.executeQuery();
			logger.info(preparedStatement.toString());
			//place the cursor at the beginning of a received data set (so it can start to read data)
			resultSet.beforeFirst();
			
			if (resultSet.next())
			{
				subject_typeRetrieved = new Subject_type();
				subject_typeRetrieved.setSubject_type(resultSet.getInt("subject_type"));
				subject_typeRetrieved.setType_name(resultSet.getString("type_name"));
			}
		}
		catch (SQLException e) 
		{
			logger.error(e.getMessage());
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
		
		return subject_typeRetrieved;
	}
}
